<template>
  <view class="page-container">
    <!-- 主要内容区域 -->
    <scroll-view class="content" scroll-y scroll-indicator="none">
      
      <!-- 顶部装饰区域 -->
      <view class="header">
        <view class="app-logo">
          <uni-icons type="image-fill" size="50" color="#ffffff"></uni-icons>
        </view>
        <view class="app-title">
          <text class="title-text">坤坤去水印工具</text>
        </view>
      </view>
      
      <!-- 支持平台提示 -->
      <view class="platform-tips">
        <text class="tips-text">✨ 当前支持：抖音</text>
      </view>
      
      <!-- 输入框区域 -->
      <view class="input-section-fixed">
        <view class="gradient-border-container">
          <input 
            class="input-field" 
            placeholder="粘贴要下载的链接" 
            placeholder-style="color:#999;" 
            v-model="inputContent" 
            @focus="onInputFocus"
            :adjust-position="false"
          /> 
        </view>
        <button class="parse-btn" @click="handleParse" :disabled="isProcessing">
          <text class="btn-text">{{ isProcessing ? '处理中...' : '✨ 一键解析' }}</text>
        </button>
      </view>
      
      <!-- 功能介绍卡片 -->
      <view class="feature-cards">
        <view class="card-item">
          <uni-icons type="lightbulb" size="24" color="#FF9800"></uni-icons>
          <text class="card-text">自动识别平台并解析</text>
        </view>
        <view class="card-item">
          <uni-icons type="link" size="24" color="#4CAF50"></uni-icons>
          <text class="card-text">支持多种链接格式</text>
        </view>
        <view class="card-item">
          <uni-icons type="download" size="24" color="#2196F3"></uni-icons>
          <text class="card-text">一键获取无水印视频</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import http from '@/utils/http.js'

export default {
  data() {
    return {
      inputContent: '',
      isProcessing: false, // 处理状态标志
      platformRules: {
        // 平台识别规则
        douyin: ['douyin.com', 'tiktok.com', 'v.douyin.com'],
        bilibili: ['bilibili.com', 'b23.tv'],
        kuaishou: ['kuaishou.com'],
        xiaohongshu: ['xiaohongshu.com']
      },
      supportedPlatforms: ['douyin'] // 当前支持的平台
    }
  },
  
  methods: {
    // 处理解析按钮点击事件
    async handleParse() {
      // 防止重复点击
      if (this.isProcessing) {
        return
      }
      
      try {
        // 1. 获取并验证输入内容
        let contentToProcess = this.inputContent.trim()
        
        // 输入框为空时，尝试读取剪切板
        if (!contentToProcess) {
          try {
            const { data } = await uni.getClipboardData()
            contentToProcess = data || ''
            if (contentToProcess) {
              this.inputContent = contentToProcess
            }
          } catch (clipboardError) {
            console.warn('无法访问剪切板:', clipboardError)
          }
        }
        
        // 再次检查处理内容
        if (!contentToProcess) {
          this.showToast('请输入或粘贴视频链接')
          return
        }
        
        // 2. 提取URL
        const url = this.extractUrlFromContent(contentToProcess)
        
        if (!url) {
          this.showToast('没有检测到有效链接')
          return
        }
        
        // 3. 检查平台支持
        const platform = this.identifyPlatform(url)
        if (platform && !this.supportedPlatforms.includes(platform)) {
          this.showToast(`当前暂不支持${this.getPlatformName(platform)}平台`)
          return
        }
        
        // 4. 开始处理，设置状态
        this.isProcessing = true
        
        // 显示加载动画
        this.showLoading('解析中...')
        
        // 5. 发送请求到后端解析
        const response = await http.post('/cli/parse', { url })
        
        // 6. 隐藏加载动画
        uni.hideLoading()
        this.isProcessing = false
        
        // 7. 处理响应结果
        if (response && response.success && response.data) {
          // 解析成功，跳转到结果页面
          uni.navigateTo({
            url: `/pages/parse/parse?urls=${encodeURIComponent(JSON.stringify(response.data))}&platform=${platform || ''}`
          })
        } else {
          // 解析失败，显示错误信息
          const errorMsg = response && response.message 
            ? response.message 
            : '解析失败，请检查链接是否正确'
          
          this.showToast(errorMsg)
        }
      } catch (error) {
        // 确保在异常情况下也重置状态
        this.isProcessing = false
        uni.hideLoading()
        
        console.error('解析过程中发生错误:', error)
        
        // 详细的错误信息处理
        let errorMessage = '解析失败，请重试'
        if (error.response) {
          errorMessage = error.response.message || '服务器响应错误'
        } else if (error.message) {
          if (error.message.includes('timeout')) {
            errorMessage = '网络请求超时，请检查网络后重试'
          } else if (error.message.includes('request:fail')) {
            errorMessage = '网络请求失败，请检查网络连接'
          } else {
            errorMessage = error.message
          }
        }
        
        this.showToast(errorMessage, 3000)
      }
    },
    
    // 提取URL
    extractUrlFromContent(content) {
      if (!content) return null
      
      // 清理内容
      content = content.replace(/\s+/g, ' ').trim()
      
      // 匹配HTTP/HTTPS URL
      const urlRegex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi
      const matches = content.match(urlRegex)
      
      if (matches && matches.length > 0) {
        // 过滤无效URL
        const validUrl = matches.find(url => 
          !url.includes('javascript:') && 
          !url.includes('data:') && 
          url.length > 10
        )
        return validUrl || matches[0]
      }
      
      // 尝试匹配短链接格式（不带协议头）
      const shortLinkRegex = /(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi
      const shortMatches = content.match(shortLinkRegex)
      
      if (shortMatches && shortMatches.length > 0) {
        // 过滤并添加协议头
        const validShortUrl = shortMatches.find(url => 
          url.length > 5 && 
          !url.includes(' ') && 
          url.includes('.')
        )
        if (validShortUrl) {
          return 'https://' + validShortUrl
        }
      }
      
      return null
    },
    
    // 识别平台
    identifyPlatform(url) {
      for (const [platform, domains] of Object.entries(this.platformRules)) {
        for (const domain of domains) {
          if (url.toLowerCase().includes(domain.toLowerCase())) {
            return platform
          }
        }
      }
      return null
    },
    
    // 获取平台中文名称
    getPlatformName(platform) {
      const platformNames = {
        douyin: '抖音',
        bilibili: 'B站',
        kuaishou: '快手',
        xiaohongshu: '小红书'
      }
      return platformNames[platform] || platform
    },
    
    // 用户点击输入框时调用
    onInputFocus() {
      // 用户主动点击输入框，可以尝试检查剪切板
      if (!this.inputContent.trim()) {
        this.checkClipboard()
      }
    },
    
    // 检查剪切板（仅在用户交互时调用）
    checkClipboard() {
      try {
        uni.getClipboardData({
          success: (res) => {
            const clipboardContent = res.data || ''
            if (clipboardContent.trim() && this.extractUrlFromContent(clipboardContent)) {
              this.inputContent = clipboardContent
            }
          }
        })
      } catch (clipboardError) {
        console.warn('无法访问剪切板:', clipboardError)
      }
    },
    
    // 显示提示信息
    showToast(title, duration = 2000) {
      uni.showToast({
        title: title,
        icon: 'none',
        duration: duration
      })
    },
    
    // 显示加载动画
    showLoading(title) {
      uni.showLoading({
        title: title,
        mask: true
      })
    }
  }
}
</script>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.content {
  flex: 1;
  padding: 0;
}

/* 顶部装饰区域 */
.header {
  background: linear-gradient(135deg, #2979FF, #1976D2);
  padding: 40px 20px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.app-logo {
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  padding: 15px;
  margin-bottom: 10px;
}

.app-title {
  margin-top: 10px;
}

.title-text {
  color: white;
  font-size: 18px;
  font-weight: bold;
}

/* 支持平台提示 */
.platform-tips {
  background-color: white;
  padding: 10px 20px;
  margin-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.tips-text {
  color: #666;
  font-size: 14px;
}

/* 输入框区域 - 固定到中间 */
.input-section-fixed {
  background-color: #f5f5f5;
  padding: 20px;
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

/* 输入框渐变边框容器 */
.gradient-border-container {
  background: linear-gradient(135deg, #90CAF9, #64B5F6, #42A5F5, #2196F3);
  border-radius: 10px;
  padding: 2px;
  margin-bottom: 15px;
  width: 100%;
}

.input-field {
  width: 100%;
  height: 90px;
  background-color: white;
  border: none;
  border-radius: 8px;
  padding: 15px;
  box-sizing: border-box;
  font-size: 16px;
  color: #333;
  resize: none;
}

/* 解析按钮 */
.parse-btn {
  width: 100%;
  height: 50px;
  background: linear-gradient(90deg, #2979FF, #3d71e9, #2969ffcf, #42A5F5);
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: bold;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s ease;
}

.parse-btn:active {
  opacity: 0.8;
  transform: scale(0.98);
}

.parse-btn:disabled {
  background: #cccccc;
  opacity: 0.8;
}

.btn-text {
  color: white;
  font-weight: bold;
}

/* 功能介绍卡片 */
.feature-cards {
  padding: 0 20px 20px;
}

.card-item {
  background-color: white;
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.card-item uni-icons {
  margin-right: 10px;
}

.card-text {
  color: #333;
  font-size: 14px;
}
</style>